# -*- coding: utf-8 -*-
from django.http import JsonResponse

import settings as miniweixin_settings
from .api import MiniWeiXinApi
from .models import BkMiniWeixinUser, BkMiniWeiXinUserSession


class MiniWeixinAccountSingleton(object):
    """
    单例基类
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        '''
        @param class_:
        '''
        if not isinstance(cls._instance, cls):
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


class MiniWeixinAccount(MiniWeixinAccountSingleton):

    def __init__(self):
        self.miniweixin_api = MiniWeiXinApi()

    def is_miniweixin_visit(self, request):
        """
        是否来自微信访问
        """
        if miniweixin_settings.USE_MINIWEIXIN and request.path.startswith(miniweixin_settings.MINIWEIXIN_SITE_URL) and \
                request.get_host() == miniweixin_settings.MINIWEIXIN_APP_EXTERNAL_HOST:
            return True
        return False

    def login(self, request):
        """
        登录
        """
        if not self.is_miniweixin_visit(request):
            # TODO 改造为友好页面
            return JsonResponse({'code': 400, 'message': u"非微信访问，或应用未启动微信访问", 'data': {}})
        code = request.body_data.get('code')
        is_code_vaild, base_data = self.miniweixin_api.check_login_code(code)
        if not is_code_vaild:
            # TODO 改造为友好页面
            return JsonResponse({'code': 400, 'message': u"登录失败", 'data': {}})
        # 设置登录
        bktoken = BkMiniWeiXinUserSession.objects.create_user_session(
            session_key=base_data.get('session_key'),
            openid=base_data.get('openid')
        )
        user = BkMiniWeixinUser.objects.get_update_or_create_user(openid=base_data.get('openid'))
        setattr(request, 'miniweixin_user', user)
        return JsonResponse({'code': 200, 'message': u"登录成功", 'data': {'bktoken': bktoken}})

    def redirect_miniweixin_login(self, request):
        """
        重定向登录
        """
        return JsonResponse({'code': 401, 'message': u"未登录或登录失效", 'data': {}})

    def update_userinfo(self, request):
        """
        更新用户信息
        """
        encrypted_data = request.body_data.get('encryptedData')
        iv = request.body_data.get('iv')
        openid = request.miniweixin_user.openid
        session = BkMiniWeiXinUserSession.objects.get(openid=openid)
        userinfo = self.miniweixin_api.get_user_info(session.session_key, encrypted_data, iv)
        if userinfo is None:
            return JsonResponse({'code': 400, 'message': u"更新用户信息失败", 'data': {}})
        userinfo.pop('openid')
        user = BkMiniWeixinUser.objects.get_update_or_create_user(openid, **userinfo)
        request.miniweixin_user = user
        return JsonResponse({'code': 200, 'message': u"更新用户信息成功", 'data': {}})
